from django.http import JsonResponse
from django.views.decorators.http import require_GET
from .models import Parts
from django.utils import timezone

@require_GET
def part_status(request):
    try:
        hours = int(request.GET.get('hours', 24))
        start_time = timezone.now() - timezone.timedelta(hours=hours)

        parts = Parts.objects.filter(
            create_time__gte=start_time
        ).values('sn', 'status')
        # 生成要分析的 QuerySet
        # queryset = Parts.objects.filter(
        #     create_time__gte='2025-05-17',
        #     status=1
        # ).order_by('-create_time')
        # sql, params = queryset.query.sql_with_params()
        # print(sql)
        # print(params)

        
        return JsonResponse({
            'count': len(parts),
            'results': list(parts)
        })
    
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


# 添加测试数据
@require_GET
def add_test_data(request):
    try:
        for i in range(10):
            Parts.objects.create(sn=f'TestPart{i}', status=0)
        
        for i in range(10, 20):
            Parts.objects.create(sn=f'TestPart{i}', status=1, create_time=timezone.now() + timezone.timedelta(days=30))
        
        for i in range(20, 30):
            Parts.objects.create(sn=f'TestPart{i}', status=2, create_time=timezone.now() + timezone.timedelta(days=60))

        return JsonResponse({'message': 'Test data added successfully'})
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)